//
//  AccountBalanceController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/24.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Moya
import ObjectMapper
import TOWebViewController
import SwiftProgressHUD
class AccountBalanceController: UIViewController {
    var applicaionBtn:UIButton?
    fileprivate var maxAmount:Double?
    fileprivate var maxDays:Int?
    fileprivate var salaryDayRate:String?
    fileprivate var salaryPrepaidperiod:String?
   fileprivate var validAccount:String?
    fileprivate var prepaidCount:Int?
    var balanceDetailLabel:UILabel = {
        let label = UILabel()
        label.textColor = UIColor.white
        label.adjustsFontSizeToFitWidth = true
        label.font = wwFont_Semibold(60)
        label.text = "00.00"
        return label
    }()
//    var mwRankingLabel:UILabel = {
//        let label = UILabel()
//        label.textColor = UIColor.white
//        label.adjustsFontSizeToFitWidth = true
//        label.font = wwFont_Regular(15)
//        label.text = "在工友中排名849位"
//        return label
//    }()
    var applyLoanAmount:Int?
    var isAmount:Bool?
    var isMoths:Bool?
    var loanDays:Int?
    var oneHundsButton:UIButton?
    var twoHundsButton:UIButton?
    var oneMonthButton:UIButton?
    var twoMonthsButton:UIButton?
    var threeMonthsButton:UIButton?
    var loanMakeSureButton:UIButton?
    var loanCancelButton:UIButton?
    var timeAlert:TWLAlertView?
    fileprivate var isCardSet:Bool?
   fileprivate var guid:String?
   fileprivate var orderNo: String?
    fileprivate var advanceView:SalaryAdvanceView?
//    fileprivate lazy var happyBuyButton : UIButton = {
//        let happyBuyButton = UIButton(type: UIButtonType.custom)
//        happyBuyButton.addTarget(self, action: #selector(happyBuyButtonClick), for: .touchUpInside)
//        happyBuyButton.setImage(UIImage.init(named: "happyBuy"), for: UIControlState.normal)
//        return happyBuyButton
//    }()
    
//    @objc fileprivate func happyBuyButtonClick(){
//        WWProgressHUD.success("近期开放，敬请期待!")
//
//    }
//    fileprivate lazy var tixianButton:UIButton = {
//        let tixianButton = UIButton(type: UIButtonType.custom)
//        tixianButton.addTarget(self, action: #selector(doWithdrawButtionAction), for: .touchUpInside)
//        tixianButton.setImage(UIImage.init(named: "lc_tixianbtn"), for: UIControlState.normal)
//        return tixianButton
//    }()
    fileprivate lazy var fangxinhuaView:FangxinhuaView = {
        let fangxinhuaView = FangxinhuaView()
        fangxinhuaView.frame = CGRect(x: 0, y: 350, width: SCREEN_WIDTH, height: 140)
      fangxinhuaView.applicationButton.layer.cornerRadius = 5
      fangxinhuaView.applicationButton.layer.masksToBounds = true
      fangxinhuaView.applicationButton.addTarget(self, action: #selector(loanApplicationClick), for: .touchUpInside)
    fangxinhuaView.advanceDetail.addTarget(self, action: #selector(advanceDetailClick), for: .touchUpInside)
      return fangxinhuaView
    }()
    
    /*
    fileprivate lazy var payRiseView:PayRiseView = {
        let payRiseView = PayRiseView()
        payRiseView.frame = CGRect(x: 0, y: 370, width: SCREEN_WIDTH, height: 58)
        let tap = UITapGestureRecognizer(target: self, action: #selector(payRiseClick(_:)))
        payRiseView.addGestureRecognizer(tap)
        return payRiseView
    }()
    */
    fileprivate lazy var withdrawView:WithDrawView = {
        let withdrawView = WithDrawView()
        withdrawView.frame = CGRect(x: 0, y: 370, width: SCREEN_WIDTH, height: 58)
        let tap = UITapGestureRecognizer(target: self, action: #selector(withdrawViewClick(_:)))
        withdrawView.addGestureRecognizer(tap)
        return withdrawView
    }()
    
    @objc fileprivate func withdrawViewClick(_ tap:UITapGestureRecognizer){
        let withDraw = WithdrawController()
        withDraw.hidesBottomBarWhenPushed = true
    self.navigationController?.pushViewController(withDraw, animated: true)
    }
    @objc fileprivate func payRiseClick(_ tap:UITapGestureRecognizer){
        
    }
    @objc fileprivate func advanceDetailClick(){
        let myPrepaid = MyPrepaidViewController(nibName: "MyPrepaidViewController", bundle: nil)
        myPrepaid.hidesBottomBarWhenPushed = true
    self.navigationController?.pushViewController(myPrepaid, animated: true)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.isAmount = false
        self.isMoths = false
        self.isCardSet = false
        self.getWebConfigSalaryPrepaidParams()
        view.backgroundColor = UIColor.white
       // self.navigationItem.title = ""
        NotificationCenter.default.addObserver(self, selector: #selector(doNotificationAction), name: NSNotification.Name.init(kNotificationWithdrawComplete), object: nil)
        
        self.setupViews()
        self.getPrepaidCountData()
        self.getSalaryPrepaidAmount()
        self.applicaionBtn = self.fangxinhuaView.applicationButton
        self.setupSalaryCardCount()
        self.getData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.hidesBottomBarWhenPushed = false
        self.setupSalaryCardCount()
        self.navigationController?.navigationBar.isHidden = true
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "", style: .done, target: nil, action: nil)

        let aNavigationBar = UINavigationBar()
        aNavigationBar.isTranslucent = false
        aNavigationBar.titleTextAttributes = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18),NSAttributedStringKey.foregroundColor: UIColor.white]//标题
        
        aNavigationBar.backgroundColor = colorWith255RGB(16, g: 142, b: 233)//背景
        aNavigationBar.barTintColor = colorWith255RGB(16, g: 142, b: 233)//背景
        aNavigationBar.setBackgroundImage(UIImage(), for: .default)
        aNavigationBar.shadowImage = UIImage()
        

        let rightButton = UIButton()
        rightButton.addTarget(self, action: #selector(doRightAction), for: .touchUpInside)
        rightButton.setTitle("明细", for: .normal)
        rightButton.setTitleColor(UIColor.white, for: .normal)
        rightButton.titleLabel?.font = wwFont_Regular(15)
        aNavigationBar.addSubview(rightButton)
        rightButton.snp.makeConstraints { (make) in
            make.right.equalTo(aNavigationBar)
            make.bottom.equalTo(aNavigationBar).offset(3)
            make.width.height.equalTo(50)
            
        }
        
//        let titleLabel = UILabel()
//        titleLabel.textColor = UIColor.white
//        titleLabel.text = "余额"
//        titleLabel.font = wwFont_Medium(18)
//        aNavigationBar.addSubview(titleLabel)
//        titleLabel.snp.makeConstraints { (make) in
//            make.centerX.equalTo(aNavigationBar)
//            make.centerY.equalTo(rightButton
//            )
//        }
        self.view.addSubview(aNavigationBar)
        aNavigationBar.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(64)
        }
        
        self.getWebConfigSalaryPrepaidParams()
        self.getPrepaidCountData()
        self.getSalaryPrepaidAmount()
        self.setupSalaryCardCount()
        self.getData()
    }
    fileprivate func getPrepaidCountData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
    LCAPiSubManager.request(.GetSalaryPrepaidCount(AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
               
                guard (jsonString["State"]) as! String == "OK" else{
                   
                    return
                }
                guard let resultDic = jsonString["Result"] as? NSDictionary else{
                    return
                }
                guard let maxCount : Int = resultDic["MaxCount"] as? Int,let haveCount : Int = resultDic["PrepaidCount"] as? Int else{
                    return
                }
                self.prepaidCount = maxCount
                
                
                
                if maxCount > haveCount{
                    self.applicaionBtn?.setTitle("申请预支", for: UIControlState.normal)
                    self.applicaionBtn?.isEnabled = true
                    self.applicaionBtn?.backgroundColor = UIColor.init(red: 0.06, green: 0.56, blue: 0.91, alpha: 1)
                    self.fangxinhuaView.advanceDetail.isHidden = true
                    
                }else{
                    self.applicaionBtn?.setTitle("当月已预支", for: UIControlState.normal)
                    self.applicaionBtn?.isEnabled = false
                    self.applicaionBtn?.backgroundColor = UIColor.lightGray
                    self.fangxinhuaView.advanceDetail.isHidden = false
                }
                
            }
        }
    }
    fileprivate func getSalaryPrepaidAmount(){
        
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
    LCAPiSubManager.request(.GetSalaryPrepaidAmount(AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
               
                guard (jsonString["State"]) as! String == "OK" else{
                self.fangxinhuaView.maxAmountLabel.text = "0"
                    return
                }
                guard let resultDic = jsonString["Result"] as? NSDictionary else{
                   return
                }
                self.maxAmount = resultDic["MaxAmount"] as? Double
                self.maxDays = resultDic["MaxDays"] as? Int
                if (self.maxAmount != nil){
                    let validAmountObj = NSNumber.init(value: self.maxAmount!)
                    let valueString = Tool.numberToMoney("\(validAmountObj)")
                 self.fangxinhuaView.maxAmountLabel.text = valueString
                }
            }
        }
    }
    fileprivate func getWebConfigSalaryPrepaidParams(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
  LCAPiSubManager.request(.GetWebConfigSalaryPrepaidParams(AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
               
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let resultDic = jsonString["Result"] as? NSDictionary else{
                    return
                }
                self.salaryDayRate = resultDic["SalaryPrepaidDayRate"] as? String
                self.salaryPrepaidperiod = resultDic["SalaryPrepaidPeriod"] as? String
            }
        }
    }
    override func viewWillDisappear(_ animated: Bool){
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
        self.navigationController?.navigationBar.isHidden = false
    }

    private func setupViews() {
        let headerImageView = UIImageView()
        headerImageView.image = UIImage(named: "background_余额")
        headerImageView.contentMode = .scaleToFill
        self.view.addSubview(headerImageView)
        headerImageView.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view).offset(64)
//            make.height.equalTo(200)
        }
        
        let balanceTitleLabel = UILabel()
        balanceTitleLabel.text = "工资总额（元）"
        balanceTitleLabel.textColor = UIColor.white
        balanceTitleLabel.font = wwFont_Medium(25)
        headerImageView.addSubview(balanceTitleLabel)
        balanceTitleLabel.snp.makeConstraints { (make) in
       // make.centerY.equalTo(headerImageView).offset(-30)
            
            make.left.equalTo(headerImageView).offset(20)
            make.top.equalTo(headerImageView).offset(0)
            make.size.equalTo(CGSize(width: 200, height: 30))
        }
        
        headerImageView.addSubview(self.balanceDetailLabel)
        self.balanceDetailLabel.snp.makeConstraints { (make) in
            make.top.equalTo(balanceTitleLabel.snp.bottom)
            make.left.equalTo(balanceTitleLabel)
            make.right.equalTo(headerImageView).offset(-10)
        make.bottom.equalTo(headerImageView).offset(-10)
        }
//        headerImageView.addSubview(self.mwRankingLabel)
//
//        self.mwRankingLabel.snp.makeConstraints { (make) in
//        make.top.equalTo(self.balanceDetailLabel.snp.bottom).offset(0)
//            make.left.equalTo(balanceTitleLabel)
//            make.right.equalTo(headerImageView).offset(-10)
//            make.height.equalTo(19)
//
//        }
        
        
//        self.view.addSubview(self.happyBuyButton)
//       // headerImageView.contentMode = .scaleToFill
//        //self.happyBuyButton.contentMode = .scaleToFill
//        self.happyBuyButton.snp.makeConstraints { (make) in
//        make.top.equalTo(headerImageView.snp.bottom).offset(12)
//            make.left.equalTo(self.view).offset(6)
//            make.right.equalTo(self.view).offset(-6)
//            make.height.equalTo(100)
//        }
        self.view.addSubview(withdrawView)
        self.withdrawView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(0)
            make.right.equalTo(self.view).offset(0)
        make.top.equalTo(headerImageView.snp.bottom).offset(0)
            make.height.equalTo(60)
        }
        
//        self.view.addSubview(payRiseView)
//        self.payRiseView.snp.makeConstraints { (make) in
//            make.left.equalTo(self.view).offset(0)
//            make.right.equalTo(self.view).offset(0)
//            make.top.equalTo(withdrawView.snp.bottom).offset(0)
//            make.height.equalTo(60)
//        }
        
        self.view.addSubview(fangxinhuaView)
        self.fangxinhuaView.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(0)
            make.right.equalTo(self.view).offset(0)
        make.top.equalTo(withdrawView.snp.bottom).offset(0)
            make.height.equalTo(184)
        }
        
//        self.view.addSubview(tixianButton)
//        self.tixianButton.snp.makeConstraints { (make) in
//            make.bottom.equalTo(self.view).offset(-50)
//            make.right.equalTo(self.view).offset(-10)
//            make.size.equalTo(CGSize(width: 80, height: 80))
//        }
    }
    
    fileprivate func setupSalaryCardCount(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        LCAPiSubManager.request(.GetSalaryCardCountData(AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let cardCount:Int = jsonString["Result"] as? Int else{
                    return
                }
                if cardCount > 0{
                    self.isCardSet = true
                }
            }
        }
    }

    func getData() {
        
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let companyId = WWUser.sharedInstance.companyID else{
            return
        }
            
    LCAPiSubManager.request(.GetAccountAmount(AccountId: accountId, CompanyID: companyId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
               if let amount = jsonString["amount"] as? Double{
                let amountObj = NSNumber.init(value: amount)
                let valueString = Tool.numberToMoney("\(amountObj)")
                self.balanceDetailLabel.text = valueString
                }
                if let validAmount = jsonString["validAmount"] as? Double{
                    
                    let validAmountObj = NSNumber.init(value: validAmount)
                    
                    let valueString = Tool.numberToMoney("\(validAmountObj)")
                    self.validAccount = valueString
                    self.withdrawView.balanceLabel.text = "可提现余额" + valueString! + "元"
                }
            }
        }
    }
    @objc func doNotificationAction() {
        self.getData()
    }
    
    @objc func doRightAction() {
 //self.navigationController?.pushViewController(SalaryFlowDetailConttroller(), animated: true)
    let salaryList = SalaryAllDetailViewController(nibName: "SalaryAllDetailViewController", bundle: nil)
    salaryList.hidesBottomBarWhenPushed = true
   self.navigationController?.pushViewController(salaryList, animated: true)
        
    }
    
    @objc fileprivate func loanApplicationClick(){
        guard (self.maxAmount != nil) else {
            return
        }
        if self.isCardSet == false {
            let alert = UIAlertController(title: "预支工资前请先绑定银行卡!", message: "", preferredStyle: .alert)
            let cancel = UIAlertAction(title: "我知道了", style: .cancel, handler: { (action) in
                
            })
            alert.addAction(cancel)
            self.present(alert, animated: true, completion: {
                
            })
            return
        }
        
        guard self.maxAmount! - 100 >= Double(0) else {
            let alert = UIAlertController(title: "可预支金额少于100.00元，请过几天再预支！", message: "", preferredStyle: .alert)
            let refuseApp = UIAlertAction(title: "我知道了", style: .cancel, handler: { (action) in
                
            })
            alert.addAction(refuseApp)
            self.present(alert, animated: true, completion: {
                
            })
            return
        }
        
        self.timeAlert = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        self.advanceView = SalaryAdvanceView.init(frame: CGRect(x: 0, y: 0, width: 280, height: 260))
        self.advanceView?.makeSureButton.addTarget(self, action: #selector(makeSureButtonFirstClick), for: .touchUpInside)
        if (self.prepaidCount != nil){
            self.advanceView?.prepaidLabel.text = "每月限定预支" + String(self.prepaidCount!) + "次"
        }
        if (self.maxAmount != nil) {
            self.advanceView?.mostMoney.text = String(self.maxAmount!)
        }
        if (self.maxDays != nil) {
            self.advanceView?.mostDays.text = String(self.maxDays!)
        }
        self.advanceView?.cancelButton.addTarget(self, action: #selector(loanSelectCancel), for: .touchUpInside)
       self.timeAlert?.initWithCustomView(self.advanceView, frame: CGRect(x: 0, y: 0, width: 280, height: 260))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.timeAlert!)
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension AccountBalanceController{
    
    @objc fileprivate func makeSureButtonFirstClick(){
        guard ((self.advanceView?.salaryNumTextField.text) != nil) &&  (self.advanceView?.salaryNumTextField.text) != "" else {
            SwiftProgressHUD.showOnlyText("请输入金额!")
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: {
                SwiftProgressHUD.hideAllHUD()
            })
            return
        }
        let selectNum = Double(self.advanceView!.salaryNumTextField!.text!)

        guard selectNum! - 100 >= Double(0) else {
            SwiftProgressHUD.showOnlyText("预支金额不能低于100元！")
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: {
                SwiftProgressHUD.hideAllHUD()
            })
            return
        }
        guard selectNum! - self.maxAmount! < Double(0) else {
            SwiftProgressHUD.showOnlyText("预支请求超额，请重新填写预支金额！")
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.5, execute: {
                SwiftProgressHUD.hideAllHUD()
            })
            return
        }
        self.timeAlert?.cancleView()
        self.timeAlert = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let advanceSureView = AdanceMakeSureView(frame: CGRect(x: 0, y: 0, width: 280, height: 135))
        advanceSureView.expenseButton.addTarget(self, action: #selector(expenseButtonClick), for: .touchUpInside)
        advanceSureView.titleLabel.text = "确认要预支" + self.advanceView!.salaryNumTextField!.text! + "元吗?"
        advanceSureView.cancelButton.addTarget(self, action: #selector(loanSelectCancel), for: .touchUpInside)
        advanceSureView.makeSureButton.addTarget(self, action: #selector(makeSureButtonClick), for: .touchUpInside)
      self.timeAlert?.initWithCustomView(advanceSureView, frame: CGRect(x: 0, y: 0, width: 280, height: 135))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.timeAlert!)
    }
    @objc fileprivate func expenseButtonClick(){
        self.timeAlert?.cancleView()
        let toWebView = TOWebViewController(urlString: PrepaidExpenseUrl)
        toWebView?.showUrlWhileLoading = false
        toWebView?.showActionButton = false
        toWebView?.showDoneButton = true
        toWebView?.hidesBottomBarWhenPushed = true
     self.navigationController?.pushViewController(toWebView!, animated: true)
    }
    @objc fileprivate func makeSureButtonClick(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let prepaidStr = self.advanceView?.salaryNumTextField.text else {
            return
        }
        
        
    LCAPiSubManager.request(.SetSalaryPrepaid(prepaidAmount: prepaidStr, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    self.timeAlert?.cancleView()
                    return
                }
                self.getPrepaidCountData()
                WWSuccess("预支成功")
            }
        }
        self.timeAlert?.cancleView()
    }
    @objc fileprivate func loanSelectCancel(){
        self.timeAlert?.cancleView()
    }

}








